<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="showDialog=true"
            > + 新增角色 </el-button>
            <!-- 表格 -->
            <el-table :data="rows">
              <el-table-column type="index" :index="indexMethod" label="序号" width="100" style="margin: 10px 0" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="clickShowAssignDialog(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="showEdit(row.id) ">编辑</el-button>
                  <el-button size="small" type="danger" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- //分页 -->
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4, 5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 公司信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        @close="closeAssignDialog"
        @open="openAssignDialog"
      >
        <el-tree
          ref="tree"
          v-loading="treeLoading"
          :data="permissionData"
          :props="{ label: 'name' }"
          :default-expand-all="true"
          :show-checkbox="true"
          :check-strictly="true"
          node-key="id"
        />

        内容部分
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="clickAssign">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">

        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button type="primary" @click="clickSubmit">确认</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </template>

      </el-dialog></div>
  </div>
</template>

<script>
import { transListToTree } from '@/utils/index'
import { reqAddRole, reqAssignPerm, reqDeleteRole, reqGetRoleDetail, reqGetRoleList, reqUpdateRole } from '@/api/setting'
import { mapState } from 'vuex'
import { reqGetCompanyById } from '@/api/copany.js'
import { reqGetPermissionList } from '@/api/permission'
export default {
  name: 'Settings',
  data() {
    return {
      treeLoading: [],
      permissionData: [],
      roleId: '',
      rows: [],
      page: 1,
      pagesize: 2,
      total: 0,
      loading: false,
      showDialog: false,
      showAssignDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: ['blur', 'change'] }]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      }
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    async getRoleList() {
      const { data: { total, rows }} = await reqGetRoleList(this.page, this.pagesize)
      this.total = total
      this.rows = rows
    },
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // 更新每页条数
      this.pagesize = val
      // 重置当前页
      this.page = 1
      // 调用方法, 重新请求
      this.getRoleList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      // 更新当前页
      this.page = val
      // 调用方法, 重新请求渲染
      this.getRoleList()
    },
    del(id) {
      this.$confirm('确认要删除该角色吗?', '温馨提示').then(async() => {
        const res = await reqDeleteRole(id)
        this.$message.success('删除角色成功')
        if (this.rows.length === 1 && this.page > 1) {
          this.page--
        }
        console.log(res, 444)
        this.getRoleList()
      }).catch(error => {
        console.log(error, '删除失败')
      })
    },
    closeDialog() {
      this.showDialog = false
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    clickSubmit() {
      this.$refs.form.validate(async flag => {
        if (!flag) return
        if (this.form.id) {
          await reqUpdateRole(this.form)
          this.$message.success('编辑角色成功')
        } else {
          await reqAddRole(this.form)
          this.$message.success('添加成功')
        }
        this.closeDialog()
        this.getRoleList()
      })
    },
    async showEdit(id) {
      // 编辑角色
      const { data } = await reqGetRoleDetail(id)
      this.showDialog = true
      this.form = data
    },
    async getCompanyInfo() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = data
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    clickShowAssignDialog(id) {
      console.log(id)
      this.roleId = id
      this.showAssignDialog = true
    },
    async openAssignDialog() {
      this.treeLoading = true
      const { data } = await reqGetPermissionList()
      this.permissionData = transListToTree(data, '0')

      const { data: roleDetail } = await reqGetRoleDetail(this.roleId)
      this.$refs.tree.setCheckedKeys(roleDetail.permIds)

      this.treeLoading = false
    },
    async clickAssign() {
      const res = await reqAssignPerm({ id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys() })
      console.log(res)
      this.$message.success('分配成功')
      this.showAssignDialog = false
    }
  }
}
</script>

<style>

</style>
